<?php
namespace App\Http\Controllers;

use App\Http\Requests\UserStatisticRequest;
use App\Models\Category;
use App\Models\Loglogin;
use App\Models\RoleUser;
use App\Models\User;
use App\Models\UserCategory;
use App\Models\UserInfo;
use App\Models\Zone;
use Illuminate\Http\Request;
use \Excel;

class UserStatisticController extends CommonController
{

    /**
     * 获取用户注册统计页面
     */
    public function getReg()
    {
        return view('userstatistic.reg');
    }

    /**
     * 获取用户登录统计页面
     */
    public function getLog()
    {
        return view('userstatistic.log');
    }

    /**
     * 获取用户性别分享页面
     */
    public function getGenderPage()
    {
        return view('userstatistic.gender');
    }

    /**
     * 获取用户性别分享页面
     */
    public function getRole()
    {
        return view('userstatistic.role');
    }

    /**
     * 获取用户关注行业分布页面
     */
    public function getIndustry()
    {
        return view('userstatistic.industry');
    }


    /**
     * 获取查询页面
     */
    public function getQuery()
    {
        return view('userstatistic.query');
    }



    public function postQuery(Request $request)
    {
        $data = $request->input();

        $data['end_time'] = strtotime($data['end_time']);
        $data['begin_time'] = strtotime($data['begin_time']);
//        dd($data);

        if('reg'==$data['type']){
            $datas = User::whereBetween('reg_time', [$data['begin_time'], $data['end_time']])->paginate(10);

            $return_date = array();
            $users_data = array();
            foreach ($datas as $k => $v) {
                $users_data[$k]['uid'] = $v->uid;
                ''!=$v->nickname?$users_data[$k]['nickname'] = $v->nickname:$users_data[$k]['nickname'] = '';
                ''!=$v->realname?$users_data[$k]['realname'] = $v->realname:$users_data[$k]['realname'] = '';
                ''!=$v->username?$users_data[$k]['username'] = $v->username:$users_data[$k]['username'] = '';

                if(0==$v->source){
                    $users_data[$k]['source'] = '网站注册';
                }elseif(1==$v->source){
                    $users_data[$k]['source'] = '投融1.0导入';
                }elseif(2==$v->source){
                    $users_data[$k]['source'] = '微信';
                }elseif(3==$v->source){
                    $users_data[$k]['source'] = '后台添加';
                }elseif(4==$v->source){
                    $users_data[$k]['source'] = '内部注册';
                }elseif(5==$v->source){
                    $users_data[$k]['source'] = '经纪人代发';
                }elseif(6==$v->source){
                    $users_data[$k]['source'] = '重庆自动注册';
                }elseif(7==$v->source){
                    $users_data[$k]['source'] = '安卓';
                }elseif(8==$v->source){
                    $users_data[$k]['source'] = 'ios';
                }else{
                    $users_data[$k]['source'] = '';
                }

                $users_data[$k]['reg_time'] = date('Y-m-d H:i:s', $v->reg_time);
            }

        }else{
            $datas = logLogin::with('user')->whereBetween('login_time', [$data['begin_time'], $data['end_time']])->paginate(10);
            $return_date = array();
            $users_data = array();
            foreach ($datas as $k => $v) {
                $users_data[$k]['uid'] = $v->uid;
                $users_data[$k]['nickname'] = isset($v->user->nickname)?$v->user->nickname:'';
                $users_data[$k]['realname'] = isset($v->user->realname)?$v->user->realname:'';
                $users_data[$k]['username'] = isset($v->user->username)?$v->user->username:'';
                if(1==$v->client_id){
                    $users_data[$k]['client_id'] = 'web登录';
                }elseif(7==$v->client_id){
                    $users_data[$k]['client_id'] = '安卓';
                }elseif(8==$v->client_id){
                    $users_data[$k]['client_id'] = 'ios';
                }else{
                    $users_data[$k]['client_id'] = '未知';
                }
                $users_data[$k]['login_time'] = date('Y-m-d H:i:s', $v->login_time);

            }
        }
        $return_date['list'] = $users_data;
        $return_date['page'] = $datas->render(true);
        $return_date['type'] = $data['type'];

        return AjaxCallbackMessage($return_date, true);
    }



    /**
     * 以Excel表格形式导出数据
     *
     */
    public function getExport(Request $request)
    {
        $data = $request->input();
        if(!$data['type'] || $data['type']==''){
            return $this->tip('操作错误，请选择类型', url('articlestatistic/query'), false);
        }

        if(!$data['begin_time'] || $data['begin_time']==''){
            return $this->tip('操作错误，请选择开始时间', url('articlestatistic/query'), false);
        }

        if(!$data['end_time'] || $data['end_time']==''){
            return $this->tip('操作错误，请选择结束时间', url('articlestatistic/query'), false);
        }

        $data['end_time'] = strtotime($data['end_time']);
        $data['begin_time'] = strtotime($data['begin_time']);

        if('reg'==$data['type']){
            $datas = User::whereBetween('reg_time', [$data['begin_time'], $data['end_time']])->get()->toArray();

//        dd($articles);

            $title = [["nickname" =>'昵称',"realname" =>'真实姓名',"username" =>'账号',"source" =>'来源',
                       "reg_time" =>'注册时间'
            ],];

            $return_data = array();
            foreach($datas as $k=>$v){
                $return_data[$k]['nickname'] = $v['nickname'];
                $return_data[$k]['realname'] = $v['realname'];
                $return_data[$k]['username'] = $v['username'];
                if(0==$v['source']){
                    $return_data[$k]['source'] = '网站注册';
                }elseif(1==$v['source']){
                    $return_data[$k]['source'] = '投融1.0导入';
                }elseif(2==$v['source']){
                    $return_data[$k]['source'] = '微信';
                }elseif(3==$v['source']){
                    $return_data[$k]['source'] = '后台添加';
                }elseif(4==$v['source']){
                    $return_data[$k]['source'] = '内部注册';
                }elseif(5==$v['source']){
                    $return_data[$k]['source'] = '经纪人代发';
                }elseif(6==$v['source']){
                    $return_data[$k]['source'] = '重庆自动注册';
                }elseif(7==$v['source']){
                    $return_data[$k]['source'] = '安卓';
                }elseif(8==$v['source']){
                    $return_data[$k]['source'] = 'ios';
                }else{
                    $return_data[$k]['source'] = '';
                }

                $return_data[$k]['reg_time'] = date('Y-m-d H:i:s', $v['reg_time']);

            }
            $regs_info = array_merge($title, $return_data);
            Excel::create('会员注册列表', function($excel) use($regs_info) {
                $excel->sheet('会员注册列表', function($sheet) use($regs_info) {
                    $sheet->rows($regs_info);
                });
            })->export('xls');

        }else{
            $datas = logLogin::with('user')->whereBetween('login_time', [$data['begin_time'], $data['end_time']])->get()->toArray();

            $title = [["nickname" =>'昵称',"realname" =>'真实姓名',"username" =>'账号',"client_id" =>'登录来源',
                       "reg_time" =>'登录时间'
            ],];

            $return_data = array();
            foreach($datas as $k=>$v){
                $return_data[$k]['nickname'] = isset($v['user']['nickname'])?$v['user']['nickname']:'';
                $return_data[$k]['realname'] = isset($v['user']['realname'])?$v['user']['realname']:'';
                $return_data[$k]['username'] = isset($v['user']['username'])?$v['user']['username']:'';

                if(1==$v['client_id']){
                    $return_data[$k]['client_id'] = 'web登录';
                }elseif(7==$v['client_id']){
                    $return_data[$k]['client_id'] = '安卓';
                }elseif(8==$v['client_id']){
                    $return_data[$k]['client_id'] = 'ios';
                }else{
                    $return_data[$k]['client_id'] = '未知';
                }

                $return_data[$k]['login_time'] = date('Y-m-d H:i:s', $v['login_time']);
            }
            $logs_info = array_merge($title, $return_data);
            Excel::create('会员登录列表', function($excel) use($logs_info) {
                $excel->sheet('会员登录列表', function($sheet) use($logs_info) {
                    $sheet->rows($logs_info);
                });
            })->export('xls');
        }

    }


    /**
     * 获取用户的城市分布
     */
    public function getCity()
    {
        return view('userstatistic.city');
    }

    /**
     * 获取用户的年龄分布
     */
    public function getAge()
    {
        return view('userstatistic.age');
    }

    /**
     *ajax获取用户日注册数据
     */
    public function getUserDayReg()
    {
        $day = 24 * 3600;
        $today_zero = strtotime('today');
        //获取今天差几个小时
        $rest = sprintf("%.2f", (24 - (time() - $today_zero) / 3600));

        $date = array();
        //获取前31天的每天凌晨的时间戳,过去的时间排在前面
        $stamps = array();
        for ($i = 30; $i >= 0; $i--) {
            $stamps[] = $today_zero - $i * $day;
            $i > 0 && $date[] = date('m-d', strtotime(-$i . " day"));
        }

        $counts = array();
        for ($i = 1; $i < 31; $i++) {
            //获取前三十天的注册数据，过去的数据放在前面
            $total = User::whereBetween('reg_time', [$stamps[$i - 1], $stamps[$i]])->count();

            //网站注册
            $web_count = User::whereBetween('reg_time', [$stamps[$i - 1], $stamps[$i]])->where('source', 0)->count();
            //投融1.0导入
            $trdr_count = User::whereBetween('reg_time', [$stamps[$i - 1], $stamps[$i]])->where('source', 1)->count();
            $weixin_count = User::whereBetween('reg_time', [$stamps[$i - 1], $stamps[$i]])->where('source', 2)->count();
            //后台添加数
            $httj_count = User::whereBetween('reg_time', [$stamps[$i - 1], $stamps[$i]])->where('source', 3)->count();
            //内部注册
            $nbzc_count = User::whereBetween('reg_time', [$stamps[$i - 1], $stamps[$i]])->where('source', 4)->count();
            //经纪人代发
            $agency_count = User::whereBetween('reg_time', [$stamps[$i - 1], $stamps[$i]])->where('source', 5)->count();
            //重庆自动注册
            $cqzc_count = User::whereBetween('reg_time', [$stamps[$i - 1], $stamps[$i]])->where('source', 6)->count();
            //安卓注册
            $ad_count = User::whereBetween('reg_time', [$stamps[$i - 1], $stamps[$i]])->where('source', 7)->count();
            //ios注册
            $ios_count = User::whereBetween('reg_time', [$stamps[$i - 1], $stamps[$i]])->where('source', 8)->count();

            $result = array('total' => $total,'web' => $web_count, 'trdr' => $trdr_count,'weixin' => $weixin_count,
                            'httj' => $httj_count,'nbzc' => $nbzc_count,'agency' => $agency_count,'cqzc' => $cqzc_count,
                            'ios' => $ios_count, 'android' => $ad_count);

            $counts[] = $result;
        }

        $today_total = User::whereBetween('reg_time', [$today_zero, time()])->count();

        //网站注册
        $today_web_count = User::whereBetween('reg_time', [$today_zero, time()])->where('source', 0)->count();
        //投融1.0导入
        $today_trdr_count = User::whereBetween('reg_time', [$today_zero, time()])->where('source', 1)->count();
        $today_weixin_count = User::whereBetween('reg_time', [$today_zero, time()])->where('source', 2)->count();
        //后台添加数
        $today_httj_count = User::whereBetween('reg_time', [$today_zero, time()])->where('source', 3)->count();
        //内部注册
        $today_nbzc_count = User::whereBetween('reg_time', [$today_zero, time()])->where('source', 4)->count();
        //经纪人代发
        $today_agency_count = User::whereBetween('reg_time', [$today_zero, time()])->where('source', 5)->count();
        //重庆自动注册
        $today_cqzc_count = User::whereBetween('reg_time', [$today_zero, time()])->where('source', 6)->count();
        //安卓注册
        $today_ad_count = User::whereBetween('reg_time', [$today_zero, time()])->where('source', 7)->count();
        //ios注册
        $today_ios_count = User::whereBetween('reg_time', [$today_zero, time()])->where('source', 8)->count();

        $today_result = array('total' => $today_total,'web' => $today_web_count, 'trdr' => $today_trdr_count,'weixin' => $today_weixin_count,
                        'httj' => $today_httj_count,'nbzc' => $today_nbzc_count,'agency' => $today_agency_count,'cqzc' => $today_cqzc_count,
                        'ios' => $today_ios_count, 'android' => $today_ad_count);

        $counts[] = $today_result;
        $date[] = '今天差' . $rest . '小时';

        $arr = [];
        foreach ($date as $k => $i) {
            $arr[] = array($i, $counts[$k]);
        }

        echo json_encode($arr);
    }

    /**
     * 获取用户周注册数据
     */
    public function getUserWeekReg()
    {
        //获取本工作周还剩下几天
        $rest = (6 - date('w')) % 7;
        $rest == 0 && $rest = 7;

        //获取上周六凌晨时间戳
        $thisSta = strtotime('today') - (7 - $rest) * 24 * 3600;

        // 定义一周的时间戳
        $week = 7 * 24 * 3600;

        //获取前30周的每周一凌晨的时间戳,从前往后排
        $stamps = array();
        $date = array();

        for ($i = 30; $i >= 0; $i--) {
            $stamps[] = $thisSta - $i * $week;
            $i > 0 && $date[] = '前' . ($i) . '周';
        }

        $counts = array();
        for ($i = 1; $i < 31; $i++) {

            $total = User::whereBetween('reg_time', [$stamps[$i - 1], $stamps[$i]])->count();
            //网站注册
            $web_count = User::whereBetween('reg_time', [$stamps[$i - 1], $stamps[$i]])->where('source', 0)->count();
            //投融1.0导入
            $trdr_count = User::whereBetween('reg_time', [$stamps[$i - 1], $stamps[$i]])->where('source', 1)->count();
            $weixin_count = User::whereBetween('reg_time', [$stamps[$i - 1], $stamps[$i]])->where('source', 2)->count();
            //后台添加数
            $httj_count = User::whereBetween('reg_time', [$stamps[$i - 1], $stamps[$i]])->where('source', 3)->count();
            //内部注册
            $nbzc_count = User::whereBetween('reg_time', [$stamps[$i - 1], $stamps[$i]])->where('source', 4)->count();
            //经纪人代发
            $agency_count = User::whereBetween('reg_time', [$stamps[$i - 1], $stamps[$i]])->where('source', 5)->count();
            //重庆自动注册
            $cqzc_count = User::whereBetween('reg_time', [$stamps[$i - 1], $stamps[$i]])->where('source', 6)->count();
            //安卓注册
            $ad_count = User::whereBetween('reg_time', [$stamps[$i - 1], $stamps[$i]])->where('source', 7)->count();
            //ios注册
            $ios_count = User::whereBetween('reg_time', [$stamps[$i - 1], $stamps[$i]])->where('source', 8)->count();

            $result = array('total' => $total,'web' => $web_count, 'trdr' => $trdr_count,'weixin' => $weixin_count,
                            'httj' => $httj_count,'nbzc' => $nbzc_count,'agency' => $agency_count,'cqzc' => $cqzc_count,
                            'ios' => $ios_count, 'android' => $ad_count);

            $counts[] = $result;
        }


        $today_total = User::whereBetween('reg_time', [$thisSta, time()])->count();
        //网站注册
        $today_web_count = User::whereBetween('reg_time', [$thisSta, time()])->where('source', 0)->count();
        //投融1.0导入
        $today_trdr_count = User::whereBetween('reg_time', [$thisSta, time()])->where('source', 1)->count();
        $today_weixin_count = User::whereBetween('reg_time', [$thisSta, time()])->where('source', 2)->count();
        //后台添加数
        $today_httj_count = User::whereBetween('reg_time', [$thisSta, time()])->where('source', 3)->count();
        //内部注册
        $today_nbzc_count = User::whereBetween('reg_time', [$thisSta, time()])->where('source', 4)->count();
        //经纪人代发
        $today_agency_count = User::whereBetween('reg_time', [$thisSta, time()])->where('source', 5)->count();
        //重庆自动注册
        $today_cqzc_count = User::whereBetween('reg_time', [$thisSta, time()])->where('source', 6)->count();
        //安卓注册
        $today_ad_count = User::whereBetween('reg_time', [$thisSta, time()])->where('source', 7)->count();
        //ios注册
        $today_ios_count = User::whereBetween('reg_time', [$thisSta, time()])->where('source', 8)->count();

        $today_result = array('total' => $today_total,'web' => $today_web_count, 'trdr' => $today_trdr_count,'weixin' => $today_weixin_count,
                              'httj' => $today_httj_count,'nbzc' => $today_nbzc_count,'agency' => $today_agency_count,'cqzc' => $today_cqzc_count,
                              'ios' => $today_ios_count, 'android' => $today_ad_count);

        $counts[] = $today_result;
        $date[] = '本周差' . $rest . '天';

        $arr = [];
        foreach ($date as $k => $i) {
            $arr[] = array($i, $counts[$k]);
        }

        echo json_encode($arr);
    }

    /**
     * 获取用户月注册数据
     */
    public function getUserMonthReg()
    {
        //获取本月还剩下多少天
        $rest = date('t') - date('j') + 1;
        //获取本月1号凌晨的时间戳
        $thisMonth = strtotime(date('Y-m-01'));
        //获取过去十三个月的，每个月1号凌晨的时间戳，从前往后
        $m = date('m');
        $y = date('Y');
        $stamps = array();

        for ($i = 0; $i < 13; $i++) {
            $newM = $m - $i;
            if ($newM <= 0) {
                $newM += 12;
                $y = $y - 1;
            }
            $stamps[] = strtotime($y . '-' . $newM . '-01');
            $y = date('Y');
        }

        $counts = array();
        for ($i = 12; $i > 0; $i--) {
            $total = User::whereBetween('reg_time', [$stamps[$i], $stamps[$i-1]])->count();
            //网站注册
            $web_count = User::whereBetween('reg_time', [$stamps[$i], $stamps[$i-1]])->where('source', 0)->count();
            //投融1.0导入
            $trdr_count = User::whereBetween('reg_time', [$stamps[$i], $stamps[$i-1]])->where('source', 1)->count();
            $weixin_count = User::whereBetween('reg_time', [$stamps[$i], $stamps[$i-1]])->where('source', 2)->count();
            //后台添加数
            $httj_count = User::whereBetween('reg_time', [$stamps[$i], $stamps[$i-1]])->where('source', 3)->count();
            //内部注册
            $nbzc_count = User::whereBetween('reg_time', [$stamps[$i], $stamps[$i-1]])->where('source', 4)->count();
            //经纪人代发
            $agency_count = User::whereBetween('reg_time', [$stamps[$i], $stamps[$i-1]])->where('source', 5)->count();
            //重庆自动注册
            $cqzc_count = User::whereBetween('reg_time', [$stamps[$i], $stamps[$i-1]])->where('source', 6)->count();
            //安卓注册
            $ad_count = User::whereBetween('reg_time', [$stamps[$i], $stamps[$i-1]])->where('source', 7)->count();
            //ios注册
            $ios_count = User::whereBetween('reg_time', [$stamps[$i], $stamps[$i-1]])->where('source', 8)->count();

            $result = array('total' => $total,'web' => $web_count, 'trdr' => $trdr_count,'weixin' => $weixin_count,
                            'httj' => $httj_count,'nbzc' => $nbzc_count,'agency' => $agency_count,'cqzc' => $cqzc_count,
                            'ios' => $ios_count, 'android' => $ad_count);

            $counts[] = $result;
        }

        $date = array();
        for ($i = 12; $i > 0; $i--) {
            //获取前12个月的文字表述，过去的表述放在前面
            $date[] = $m - $i < 1 ? '去年' . ($m - $i + 12) . '月' : $m - $i . '月';
        }

        $today_total = User::whereBetween('reg_time', [$thisMonth, time()])->count();
        //网站注册
        $today_web_count = User::whereBetween('reg_time', [$thisMonth, time()])->where('source', 0)->count();
        //投融1.0导入
        $today_trdr_count = User::whereBetween('reg_time', [$thisMonth, time()])->where('source', 1)->count();
        $today_weixin_count = User::whereBetween('reg_time', [$thisMonth, time()])->where('source', 2)->count();
        //后台添加数
        $today_httj_count = User::whereBetween('reg_time', [$thisMonth, time()])->where('source', 3)->count();
        //内部注册
        $today_nbzc_count = User::whereBetween('reg_time', [$thisMonth, time()])->where('source', 4)->count();
        //经纪人代发
        $today_agency_count = User::whereBetween('reg_time', [$thisMonth, time()])->where('source', 5)->count();
        //重庆自动注册
        $today_cqzc_count = User::whereBetween('reg_time', [$thisMonth, time()])->where('source', 6)->count();
        //安卓注册
        $today_ad_count = User::whereBetween('reg_time', [$thisMonth, time()])->where('source', 7)->count();
        //ios注册
        $today_ios_count = User::whereBetween('reg_time', [$thisMonth, time()])->where('source', 8)->count();

        $today_result = array('total' => $today_total,'web' => $today_web_count, 'trdr' => $today_trdr_count,'weixin' => $today_weixin_count,
                              'httj' => $today_httj_count,'nbzc' => $today_nbzc_count,'agency' => $today_agency_count,'cqzc' => $today_cqzc_count,
                              'ios' => $today_ios_count, 'android' => $today_ad_count);

        $counts[] = $today_result;

        $date[] = '本月差' . $rest . '天';

        $arr = [];
        foreach ($date as $k => $i) {
            $arr[] = array($i, $counts[$k]);
        }

        echo json_encode($arr);
    }

    /**
     * 获取用户日登录数
     */
    public function getUserDayLog()
    {
//        $day = 24 * 3600;
//        $today_zero = strtotime('today');
//        //获取今天差几个小时
//        $rest = sprintf("%.2f", (24 - (time() - $today_zero) / 3600));
//
//        $date = array();
//        //获取前31天的每天凌晨的时间戳,过去的时间排在前面
//        $stamps = array();
//        for ($i = 30; $i >= 0; $i--) {
//            $stamps[] = $today_zero - $i * $day;
//            $i > 0 && $date[] = date('m-d', strtotime(-$i . " day"));
//        }
//
//        $counts = array();
//        for ($i = 1; $i < 31; $i++) {
//            //获取前三十天的登录数据，过去的数据放在前面
//            $counts[] = Loglogin::whereBetween('login_time', [$stamps[$i - 1], $stamps[$i]])->count();
//        }
//
//        $counts[] = Loglogin::whereBetween('login_time', [$today_zero, time()])->count();
//        $date[] = '今天差' . $rest . '小时';
//
//        $arr = [];
//        foreach ($date as $k => $i) {
//            $arr[] = array($i, $counts[$k]);
//        }
//
//        echo json_encode($arr);
        $day = 24 * 3600;
        $today_zero = strtotime('today');
        //获取今天差几个小时
        $rest = sprintf("%.2f", (24 - (time() - $today_zero) / 3600));

        $date = array();
        //获取前31天的每天凌晨的时间戳,过去的时间排在前面
        $stamps = array();
        for ($i = 30; $i >= 0; $i--) {
            $stamps[] = $today_zero - $i * $day;
            $i > 0 && $date[] = date('m-d', strtotime(-$i . " day"));
        }

        $counts = array();
        for ($i = 1; $i < 31; $i++) {
            //获取前三十天的web登录数据
            $web = logLogin::whereBetween('login_time', [$stamps[$i - 1], $stamps[$i]])->where('client_id',1)->count();


            //获取前三十天的ios登录数据
            $ios = logLogin::whereBetween('login_time', [$stamps[$i - 1], $stamps[$i]])->where('client_id',8)->count();

            //获取前三十天的android登录数据
            $andriod = logLogin::whereBetween('login_time', [$stamps[$i - 1], $stamps[$i]])->where('client_id',7)->count();

            $total = $ios+$andriod+$web;

            $result = array('total' => $total,'web' => $web, 'ios' => $ios, 'android' => $andriod);
            $counts[] = $result;
        }

        $today_web = logLogin::whereBetween('login_time', [$today_zero, time()])->where('client_id',1)->count();

        $today_ios = logLogin::whereBetween('login_time', [$today_zero, time()])->where('client_id',8)->count();

        $today_android = logLogin::whereBetween('login_time', [$today_zero, time()])->where('client_id',7)->count();
        $total_total = $today_ios+$today_web+$today_android;

        $today_result = array('total' => $total_total,'web' => $today_web, 'ios' => $today_ios, 'android' => $today_android);
        $counts[] = $today_result;
        $date[] = '今天差' . $rest . '小时';

        $arr = [];
        foreach ($date as $k => $i) {
            $arr[] = array($i, $counts[$k]);
        }
//        dd($arr);

        echo json_encode($arr);
    }

    /**
     * 获取用户周登录数
     */
    public function getUserWeekLog()
    {
//        //获取本周还剩下几天
//        $rest = (8 - date('w')) % 7;
//        $rest == 0 && $rest = 7;
//
//        //获取本周一凌晨时间戳
//        $thisMonday = strtotime('today') - (7 - $rest) * 24 * 3600;
//
//        // 定义一周的时间戳
//        $week = 7 * 24 * 3600;
//
//        //获取前30周的每周一凌晨的时间戳,从前往后排
//        $stamps = array();
//        $date = array();
//
//        for ($i = 30; $i >= 0; $i--) {
//            $stamps[] = $thisMonday - $i * $week;
//            $i > 0 && $date[] = '前' . ($i) . '周';
//        }
//
//        $counts = array();
//        for ($i = 1; $i < 31; $i++) {
//            $counts[] = Loglogin::whereBetween('login_time', [$stamps[$i - 1], $stamps[$i]])->count();
//        }
//        $counts[] = Loglogin::whereBetween('login_time', [$thisMonday, time()])->count();
//        $date[] = '本周差' . $rest . '天';
//
//        $arr = [];
//        foreach ($date as $k => $i) {
//            $arr[] = array($i, $counts[$k]);
//        }
//
//        echo json_encode($arr);


        //获取本工作周还剩下几天
        $rest = (6 - date('w')) % 7;
        $rest == 0 && $rest = 7;


        //获取上周六凌晨时间戳
        $thisSta = strtotime('today') - (7 - $rest) * 24 * 3600;


        // 定义一周的时间戳
        $week = 7 * 24 * 3600;

        //获取前30周的每周一凌晨的时间戳,从前往后排
        $stamps = array();
        $date = array();

        for ($i = 30; $i >= 0; $i--) {
            $stamps[] = $thisSta - $i * $week;
            $i > 0 && $date[] = '前' . ($i) . '周';
        }

        $counts = array();
        for ($i = 1; $i < 31; $i++) {

            //获取前三十周的web登录数据
            $web = logLogin::whereBetween('login_time', [$stamps[$i - 1], $stamps[$i]])->where('client_id',1)->count();

            //获取前三十周的ios登录数据
            $ios = logLogin::whereBetween('login_time', [$stamps[$i - 1], $stamps[$i]])->where('client_id',8)->count();

            //获取前三十周的android登录数据
            $andriod = logLogin::whereBetween('login_time', [$stamps[$i - 1], $stamps[$i]])->where('client_id',7)->count();

            $total = $web+$ios+$andriod;

            $result = array('total' => $total,'web' => $web, 'ios' => $ios, 'android' => $andriod);
            $counts[] = $result;
        }



        $today_web = logLogin::whereBetween('login_time', [$thisSta, time()])->where('client_id',1)->count();

        $today_ios = logLogin::whereBetween('login_time', [$thisSta, time()])->where('client_id',8)->count();

        $today_android = logLogin::whereBetween('login_time', [$thisSta, time()])->where('client_id',7)->count();

        $today_total=$today_web+$today_ios+$today_android;

        $today_result = array('total' => $today_total,'web' => $today_web, 'ios' => $today_ios, 'android' => $today_android);
        $counts[] = $today_result;
        $date[] = '本周差' . $rest . '天';

        $arr = [];
        foreach ($date as $k => $i) {
            $arr[] = array($i, $counts[$k]);
        }

//        dd($arr);
        echo json_encode($arr);
    }

    /**
     * 获取用户月登录数
     */
    public function getUserMonthLog()
    {
//        //获取本月还剩下多少天
//        $rest = date('t') - date('j') + 1;
//        //获取本月1号凌晨的时间戳
//        $thisMonth = strtotime(date('Y-m-01'));
//        //获取过去十三个月的，每个月1号凌晨的时间戳，从前往后
//        $m = date('m');
//        $y = date('Y');
//        $stamps = array();
//        for ($i = 0; $i < 13; $i++) {
//            $newM = $m - $i;
//            if ($newM <= 0) {
//                $newM += 12;
//                $y = $y - 1;
//            }
//            $stamps[] = strtotime($y . '-' . $newM . '-01');
//            $y = date('Y');
//        }
//
//        $counts = array();
//        for ($i = 12; $i > 0; $i--) {
//            //获取前12个月的注册数据，过去的数据放在前面
//            $counts[] = Loglogin::whereBetween('login_time', [$stamps[$i], $stamps[$i - 1]])->count();
//        }
//
//        $date = array();
//        for ($i = 12; $i > 0; $i--) {
//            //获取前12个月的文字表述，过去的表述放在前面
//            $date[] = $m - $i < 1 ? '去年' . ($m - $i + 12) . '月' : $m - $i . '月';
//        }
//
//        $counts[] = Loglogin::whereBetween('login_time', [$thisMonth, time()])->count();
//        $date[] = '本月差' . $rest . '天';
//
//        $arr = [];
//        foreach ($date as $k => $i) {
//            $arr[] = array($i, $counts[$k]);
//        }
//
//        echo json_encode($arr);


        //获取本月还剩下多少天
        $rest = date('t') - date('j') + 1;
        //获取本月1号凌晨的时间戳
        $thisMonth = strtotime(date('Y-m-01'));
        //获取过去十三个月的，每个月1号凌晨的时间戳，从前往后
        $m = date('m');
        $y = date('Y');
        $stamps = array();
        for ($i = 0; $i < 13; $i++) {
            $newM = $m - $i;
            if ($newM <= 0) {
                $newM += 12;
                $y = $y - 1;
            }
            $stamps[] = strtotime($y . '-' . $newM . '-01');
            $y = date('Y');
        }

        $counts = array();
        for ($i = 12; $i > 0; $i--) {
            //获取前12个月的web登录数据
            $web = logLogin::whereBetween('login_time', [$stamps[$i], $stamps[$i-1]])->where('client_id',1)->count();

            //获取前12个月的ios登录数据
            $ios = logLogin::whereBetween('login_time', [$stamps[$i], $stamps[$i-1]])->where('client_id',8)->count();

            //获取前12个月的android登录数据
            $andriod = logLogin::whereBetween('login_time', [$stamps[$i], $stamps[$i-1]])->where('client_id',7)->count();

            $total = $web+$ios+$andriod;

            $result = array('total' => $total,'web' => $web, 'ios' => $ios, 'android' => $andriod);
            $counts[] = $result;
        }

        $date = array();
        for ($i = 12; $i > 0; $i--) {
            //获取前12个月的文字表述，过去的表述放在前面
            $date[] = $m - $i < 1 ? '去年' . ($m - $i + 12) . '月' : $m - $i . '月';
        }

        $today_web = logLogin::whereBetween('login_time', [$thisMonth, time()])->where('client_id',1)->count();

        $today_ios = logLogin::whereBetween('login_time', [$thisMonth, time()])->where('client_id',8)->count();

        $today_android = logLogin::whereBetween('login_time', [$thisMonth, time()])->where('client_id',7)->count();

        $today_total=$today_web+$today_ios+$today_android;

        $today_result = array('total' => $today_total,'web' => $today_web, 'ios' => $today_ios, 'android' => $today_android);
        $counts[] = $today_result;
        $counts[] = $today_result;
        $date[] = '本月差' . $rest . '天';

        $arr = [];
        foreach ($date as $k => $i) {
            $arr[] = array($i, $counts[$k]);
        }

        echo json_encode($arr);
    }





    /**
     * 导出数据
     */
    public function getExports(Request $request)
    {
        $data = $request->input();
        if (!$data['type'] || $data['type'] == '') {
            return $this->tip('操作错误，请选择类型', url('userstatistic/index'), false);
        }

        if (!$data['begin_time'] || $data['begin_time'] == '') {
            return $this->tip('操作错误，请选择开始时间', url('userstatistic/index'), false);
        }

        if (!$data['end_time'] || $data['end_time'] == '') {
            return $this->tip('操作错误，请选择结束时间', url('userstatistic/index'), false);
        }
        $data['end_time'] = strtotime($data['end_time']);
        $data['begin_time'] = strtotime($data['begin_time']);

        $users = User::with('zone', 'institution')->whereBetween('reg_time', [$data['begin_time'], $data['end_time']])->get()->toArray();

//        dd($users);
        $title = [
            [
                "uid"                   => '用户id',
                "realname"              => '真实名称',
                "idcard"                => '身份证号码',
                "nickname"              => '昵称',
                "username"              => '用户名',
                "zone"                  => '地区',
                "email"                 => '邮箱',
                "reg_ip"                => '注册ip',
                "reg_time"              => '注册时间',
                "last_ip"               => '最后登录ip',
                "last_time"             => '最后登录时间',
                "login_count"           => '登录次数',
                "score"                 => '积分',
                "gold"                  => '金币',
                "cash"                  => '现金',
                "status"                => '状态',
                "is_verify_email"       => '邮箱是否验证',
                "is_verify_tel"         => '电话是否验证',
                "is_realname_auth"      => '真实名称是否验证',
                "is_privacy_phone"      => '电话是否公开',
                "is_privacy_address"    => '地址是否公开',
                "invest_project_period" => '投资偏好阶段',
                "fund_min"              => '投资金额（最小,单位：元）',
                "fund_max"              => '投资金额（最大,单位:元）',
                "work_experience"       => '工作经历',
                "invest_views"          => '投资数量',
                "recommend"             => '是否推荐',
                "stick"                 => '是否置顶',
                "source"                => '注册来源',
                "device_identifier"     => '设备标识符',
                "is_ztc"                => '是否直通车用户',
                "institution"           => '机构',
                "is_huanxin"            => '是否环信用户',
                "client_type"           => '当前登录设备',

            ],
        ];

        $usersInfo = array();
        foreach ($users as $k => $v) {
            $usersInfo[$k]['uid'] = $v['uid'];
            $usersInfo[$k]['realname'] = $v['realname'];
            $usersInfo[$k]['idcard'] = $v['idcard'];
            $usersInfo[$k]['nickname'] = $v['nickname'];
            $usersInfo[$k]['username'] = $v['username'];
            $usersInfo[$k]['zone'] = $v['zone']['name'];
            $usersInfo[$k]['email'] = $v['email'];
            $usersInfo[$k]['reg_ip'] = $v['reg_ip'];
            $usersInfo[$k]['reg_time'] = date('Y-m-d H:i:s', $v['reg_time']);
            $usersInfo[$k]['last_ip'] = $v['last_ip'];
            $usersInfo[$k]['last_time'] = date('Y-m-d H:i:s', $v['last_time']);
            $usersInfo[$k]['login_count'] = $v['login_count'];
            $usersInfo[$k]['score'] = $v['score'];
            $usersInfo[$k]['gold'] = $v['gold'];
            $usersInfo[$k]['cash'] = $v['cash'];
            if ($v['status'] == -1) {
                $usersInfo[$k]['status'] = '冻结';
            } elseif ($v['status'] == 0) {
                $usersInfo[$k]['status'] = '未激活';
            } elseif ($v['status'] == 1) {
                $usersInfo[$k]['status'] = '正常';
            }
            $usersInfo[$k]['is_verify_email'] = $v['is_verify_email'] ? '已验证' : '未验证';
            $usersInfo[$k]['is_verify_tel'] = $v['is_verify_tel'] ? '已验证' : '未验证';
            $usersInfo[$k]['is_realname_auth'] = $v['is_realname_auth'] ? '已验证' : '未验证';
            $usersInfo[$k]['is_privacy_phone'] = $v['is_privacy_phone'] ? '公开' : '不公开';
            $usersInfo[$k]['is_privacy_address'] = $v['is_privacy_address'] ? '公开' : '不公开';
            $usersInfo[$k]['invest_project_period'] = $v['invest_project_period'];
            $usersInfo[$k]['invest_project_period'] = $v['invest_project_period'];
            $usersInfo[$k]['fund_min'] = $v['fund_min'];
            $usersInfo[$k]['fund_max'] = $v['fund_max'];
            $usersInfo[$k]['work_experience'] = $v['work_experience'];
            $usersInfo[$k]['invest_views'] = $v['invest_views'];
            $usersInfo[$k]['recommend'] = $v['recommend'] ? '推荐' : '不推荐';
            $usersInfo[$k]['stick'] = $v['stick'] ? '置顶' : '不置顶';
            $usersInfo[$k]['source'] = $v['source'];
            $usersInfo[$k]['device_identifier'] = $v['device_identifier'];
            $usersInfo[$k]['is_ztc'] = $v['is_ztc'] ? '是' : '不是';
            $usersInfo[$k]['institution'] = $v['institution']['subject'];
            $usersInfo[$k]['is_huanxin'] = $v['is_huanxin'] ? '是' : '不是';
            $usersInfo[$k]['client_type'] = $v['client_type'];
        }
        $usersInfo = array_merge($title, $usersInfo);
        Excel::create(
            '会员注册列表',
            function ($excel) use ($usersInfo) {
                $excel->sheet(
                    '会员注册列表',
                    function ($sheet) use ($usersInfo) {
                        $sheet->rows($usersInfo);
                    }
                );
            }
        )->export('xls');
    }

    public function postFind(UserStatisticRequest $request)
    {
        $data = $request->input();
        $data['end_time'] = strtotime($data['end_time']);
        $data['begin_time'] = strtotime($data['begin_time']);
        $users = User::with('zone', 'institution')->whereBetween('reg_time', [$data['begin_time'], $data['end_time']])->paginate(10);
        $return_date = array();
        $users_data = array();
        foreach ($users as $k => $v) {
            $users_data[$k]['uid'] = $v->uid;
            $users_data[$k]['nickname'] = $v->nickname ? $v->nickname : '';
            $users_data[$k]['username'] = $v->username;
            $users_data[$k]['reg_time'] = date('Y-m-d H:i:s', $v->reg_time);
            $users_data[$k]['login_count'] = $v->login_count;
            if ($v->status == -1) {
                $users_data[$k]['status'] = '冻结';
            } elseif ($v->status == 0) {
                $users_data[$k]['status'] = '未激活';
            } elseif ($v->status == 1) {
                $users_data[$k]['status'] = '正常';
            }
            $users_data[$k]['recommend'] = $v->recommend ? '推荐' : '暂不推荐';
        }
        $return_date['list'] = $users_data;
        $return_date['page'] = $users->render(true);

        return AjaxCallbackMessage($return_date, true);
    }

    /**
     * 获取用户昨天注册的来源
     */
    public function getRegIp()
    {
    }

    /**
     *获取性别比例
     */
    public function getGender()
    {
        $genders = UserInfo::get()->lists('gender');

        $male = $female = $unknown = 0;

        foreach ($genders as $k => $v) {
            if (0 == $v) {
                $female += 1;
            } elseif (1 == $v) {
                $male += 1;
            } else {
                $unknown += 1;
            }
        }

        $arr = array('男' => $male, '女' => $female, '未知' => $unknown);
        echo json_encode($arr);
    }

    /**
     * 获取角色分布数据
    */
    public function getRoleData()
    {
        $roles = RoleUser::get()->lists('role_id');

        $project = $investor = $maker = 0;

        foreach ($roles as $k => $v) {
            if (2 == $v) {
                $project += 1;
            } elseif (3 == $v) {
                $investor += 1;
            } elseif (4 == $v) {
                $maker += 1;
            }
        }

        $arr = array('项目方' => $project, '投资人' => $investor, '创客空间' => $maker);
        echo json_encode($arr);
    }

    /**
     * 获取行业分布数据
     */
    public function getIndustryData()
    {

        $userCategories = UserCategory::get()->lists('category_id');
        $categories = Category::lists('name', 'id');
//        dd($categories);

        $arr = $category_ids = array();
        foreach ($categories as $k => $v) {
            $arr[$v] = 0;
            $category_ids[] = $k;
        }

        foreach ($userCategories as $k => $v) {
            if (in_array($v, $category_ids)) {
                $arr[$categories[$v]] = $arr[$categories[$v]] + 1;
            }
        }

        echo json_encode($arr);
    }

    /**
     * 获取用户城市分布 todo
     */
    public function getCityData()
    {
        $zone_ids = User::get()->lists('zone_id');

        $zones = Zone::with('zone')->get();
        $shanghai = $beijing = $tianjin = $chongqing = array();
        foreach ($zones as $k => $v) {
            if (isset($v->zone->name) && $v->zone->name == '北京市') {
                $beijing[] = $v;
            }

            if (isset($v->zone->name) && $v->zone->name == '上海市') {
                $shanghai[] = $v;
            }

            if (isset($v->zone->name) && $v->zone->name == '天津市') {
                $tianjin[] = $v;
            }

            if (isset($v->zone->name) && $v->zone->name == '重庆市') {
                $chongqing[] = $v;
            }
        }
    }

    /**
     * 获取用户年龄分布
     */
    public function getAgeData()
    {
        $ages = UserInfo::lists('birthday');
        $now = explode('-', date('Y-m-d', time()))[0] - 100;

        $stamps = array();
        foreach ($ages as $k => $v) {
            $val = explode('-', $v);
            if ($val[0] > $now) {
                $stamps[] = (time() - strtotime($v)) / (365 * 24 * 3600);
            } else {
                $stamps[] = '年龄数据有问题或为空值';
            }
        }

        $blowTwenty = $twenty = $thirty = $forty = $fifty = $sixty = $seventy = $question = 0;
        foreach ($stamps as $k => $value) {
            if (is_numeric($value)) {
                if ($value < 20) {
                    $blowTwenty += 1;
                } elseif ($value >= 20 && $value < 30) {
                    $twenty += 1;
                } elseif ($value >= 30 && $value < 40) {
                    $thirty += 1;
                } elseif ($value >= 40 && $value < 50) {
                    $forty += 1;
                } elseif ($value >= 50 && $value < 60) {
                    $fifty += 1;
                } elseif ($value >= 60 && $value < 70) {
                    $sixty += 1;
                } elseif ($value >= 70) {
                    $seventy += 1;
                }
            } else {
                $question += 1;
            }
        }

        $arr = array('二十以下' => $blowTwenty, '二十至三十' => $twenty, '三十至四十' => $thirty, '四十至五十' => $forty, '五十至六十' => $fifty, '六十至七十' => $sixty, '七十以上' => $seventy, '年龄数据有问题或为空值' => $question);

        echo json_encode($arr);
    }
}